<?php declare(strict_types=1);

/**
 * @package EzPortalMigration (Light Portal)
 * @link https://custom.simplemachines.org/index.php?mod=4244
 * @author Bugo <bugo@dragomano.ru>
 * @copyright 2021-2025 Bugo
 * @license https://spdx.org/licenses/GPL-3.0-or-later.html GPL-3.0-or-later
 *
 * @category plugin
 * @version 08.11.25
 */

namespace LightPortal\Plugins\EzPortalMigration;

use Bugo\Bricks\Tables\IdColumn;
use Bugo\Compat\User;
use Laminas\Db\Sql\Expression;
use LightPortal\DataHandlers\Imports\Database\AbstractDatabasePageImport;
use LightPortal\Enums\EntryType;
use LightPortal\UI\Tables\CheckboxColumn;
use LightPortal\UI\Tables\PageSlugColumn;
use LightPortal\UI\Tables\TitleColumn;
use LightPortal\Utils\DateTime;

if (! defined('LP_NAME'))
	die('No direct access...');

class PageImport extends AbstractDatabasePageImport
{
	protected string $langKey = 'lp_ez_portal_migration';

	protected string $formAction = 'import_from_ez';

	protected string $uiTableId = 'ez_pages';

	protected function defineUiColumns(): array
	{
		return [
			IdColumn::make()
				->setSort('id_page'),
			PageSlugColumn::make()
				->setSort('title DESC', 'title'),
			TitleColumn::make()
				->setData('title', 'word_break'),
			CheckboxColumn::make(entity: 'pages'),
		];
	}

	public function getAll(int $start = 0, int $limit = 0, string $sort = 'id_page'): array
	{
		if (! $this->sql->tableExists('ezp_page')) {
			return [];
		}

		$select = $this->sql->select()
			->from('ezp_page')
			->columns(['id_page', 'date', 'title', 'views'])
			->order($sort)
			->limit($limit)
			->offset($start);

		$result = $this->sql->execute($select);

		$items = [];
		foreach ($result as $row) {
			$items[$row['id_page']] = [
				'id'         => $row['id_page'],
				'slug'       => $this->generateSlug(['english' => $row['title']]),
				'type'       => 'html',
				'status'     => 1,
				'num_views'  => $row['views'],
				'author_id'  => User::$me->id,
				'created_at' => DateTime::relative($row['date']),
				'title'      => $row['title'],
			];
		}

		return $items;
	}

	public function getTotalCount(): int
	{
		if (! $this->sql->tableExists('ezp_page')) {
			return 0;
		}

		$select = $this->sql->select()
			->from('ezp_page')
			->columns(['count' => new Expression('COUNT(*)')]);

		$result = $this->sql->execute($select)->current();

		return (int) $result['count'];
	}

	protected function getItems(array $ids): array
	{
		$select = $this->sql->select()
			->from('ezp_page')
			->columns(['id_page', 'date', 'title', 'content', 'views', 'permissions']);

		if ($ids !== []) {
			$select->where->in('id_page', $ids);
		}

		$result = $this->sql->execute($select);

		$items = [];
		foreach ($result as $row) {
			$items[$row['id_page']] = [
				'page_id'         => $row['id_page'],
				'category_id'     => 0,
				'author_id'       => User::$me->id,
				'slug'            => $this->generateSlug(['english' => $row['title']]),
				'description'     => '',
				'content'         => $row['content'],
				'type'            => 'html',
				'entry_type'      => EntryType::DEFAULT->name(),
				'permissions'     => $this->getPermission($row),
				'status'          => 1,
				'num_views'       => $row['views'],
				'num_comments'    => 0,
				'created_at'      => $row['date'],
				'updated_at'      => 0,
				'deleted_at'      => 0,
				'last_comment_id' => 0,
				'title'           => $row['title'],
			];
		}

		return $items;
	}

	protected function extractPermissions(array $row): int|array
	{
		return array_map(intval(...), explode(',', (string) $row['permissions']));
	}
}
